package com.aj.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.aj.activity.dialog.ChooseDateDialog;
import com.aj.activity.dialog.ChooseDateDialog.IChooseDay;
import com.aj.application.LoveHomeApplication;
import com.aj.databases.dao.UserDao;
import com.aj.databases.entry.User;
import com.aj.http.AsynchronizationHttpRequest.IHttpCallBack;
import com.aj.http.request.ManagerPetRequest;
import com.aj.http.request.UploadPhotoRequest;
import com.aj.http.response.BaseRespond;
import com.aj.http.response.Common;
import com.aj.http.response.UploadPhotoResponse;
import com.aj.utils.MobileUtil;
import com.aj.utils.PortraitLoaderUtil;

public class AddPetActivity extends BaseActivity implements IChooseDay {

	private ImageView header;
	private EditText enter_nickname;
	private EditText enter_age;
	private EditText enter_birth;
	private RadioGroup sex_radiogroup;
	private Button sure_button;
	private Button cannel_button;

	private String sex = "0";

	private UserDao userDao;
	private User user;

	protected static final int ITEM_CARTOON = 0;
	protected static final int ITEM_CAMERA = 1;
	protected static final int ITEM_PICTURE = 2;
	protected static final int ITEM_CANCEL = 3;
	private Bitmap portraitBitmap;
	private String photoUrl = "";
	protected static final String[] MENU_NAME_ARRAY = new String[4];
	private ListView menuList;

	private ChooseDateDialog chooseDateDialog;

	private void showChooseDate() {
		if (chooseDateDialog == null) {
			chooseDateDialog = new ChooseDateDialog(AddPetActivity.this);
			chooseDateDialog.setChooseDay(AddPetActivity.this);
		}
		chooseDateDialog.show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_pet);
		setActionBarTitle("宠物管理");
		initView();
	}

	private void initView() {
		header = (ImageView) findViewById(R.id.header);
		userDao = new UserDao(this);
		user = userDao.getCurrentUser(LoveHomeApplication.token);
		enter_nickname = (EditText) findViewById(R.id.enter_nickname);
		enter_age = (EditText) findViewById(R.id.enter_age);
		enter_birth = (EditText) findViewById(R.id.enter_birth);
		sure_button = (Button) findViewById(R.id.sure_button);
		cannel_button = (Button) findViewById(R.id.cannel_button);
		sex_radiogroup = (RadioGroup) findViewById(R.id.sex_radiogroup);
		userDao = new UserDao(this);
		user = userDao.getCurrentUser(LoveHomeApplication.token);
		MENU_NAME_ARRAY[0] = getString(R.string.userinfo_systemheader_text);
		MENU_NAME_ARRAY[1] = getString(R.string.userinfo_photograph_text);
		MENU_NAME_ARRAY[2] = getString(R.string.userinfo_gallery_text);
		MENU_NAME_ARRAY[3] = getString(R.string.dialog_cannel_text);
		createMenu();
		sex_radiogroup
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						switch (checkedId) {
						case R.id.male:
							sex = "0";
							break;
						case R.id.female:
							sex = "1";
							break;
						}
					}
				});
		ButtonClick buttonClick = new ButtonClick();
		enter_birth.setFocusable(false);
		enter_birth.setOnClickListener(buttonClick);
		header.setOnClickListener(buttonClick);
		sure_button.setOnClickListener(buttonClick);
		cannel_button.setOnClickListener(buttonClick);
	}

	class ButtonClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.header:
				openPanel();
				break;
			case R.id.enter_birth:
				showChooseDate();
				break;
			case R.id.sure_button:
				if (enter_nickname.getText().toString().trim().length() == 0) {
					Toast.makeText(AddPetActivity.this, "请输入宠物昵称~",
							Toast.LENGTH_LONG).show();
					return;
				}
				showProgressDialog();
				new ManagerPetRequest().excute(AddPetActivity.this, user
						.getUser_id(), "1", null, photoUrl, enter_nickname
						.getText().toString(), sex, enter_birth.getText()
						.toString(), new IHttpCallBack() {
					@Override
					public void success(String result) {
						try {
							dimissProgressDialog();
							Common common = new Common(new JSONObject(result));
							if (common.getReturnCode().equals(
									BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
								AddPetActivity.this.finish();
							}
							Toast.makeText(AddPetActivity.this,
									common.getErrorMsg(), Toast.LENGTH_LONG)
									.show();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void fail(String result) {
						try {
							dimissProgressDialog();
							Common common = new Common(new JSONObject(result));
							Toast.makeText(AddPetActivity.this,
									common.getErrorMsg(), Toast.LENGTH_LONG)
									.show();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
				break;
			case R.id.cannel_button:
				finish();
				break;
			}
		}

	}

	private void createMenu() {
		View view = LayoutInflater.from(AddPetActivity.this).inflate(
				R.layout.menu_choose_dialog, null);
		menuList = (ListView) view.findViewById(R.id.menulist);
		menuList.setAdapter(getMenuAdapter(MENU_NAME_ARRAY));
		setMenuLayout(menuList);
		menuList.setOnItemClickListener(new ItemClickEvent());
	}

	class ItemClickEvent implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Intent intent;
			switch (arg2) {
			case ITEM_CARTOON:
				// startAccountPortraitGridActivity();
				Toast.makeText(AddPetActivity.this, "点击了系统头像",
						Toast.LENGTH_LONG).show();
				break;
			case ITEM_CAMERA:
				intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, 1);
				break;
			case ITEM_PICTURE:
				intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				intent.setType("image/*");
				intent.putExtra("crop", "true");
				intent.putExtra("aspectX", 1);
				intent.putExtra("aspectY", 1);
				intent.putExtra("outputX", 80);
				intent.putExtra("outputY", 80);
				intent.putExtra("return-data", true);
				startActivityForResult(intent, 2);
				break;
			case ITEM_CANCEL:
				break;
			}
			closePanel();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			if (data.getExtras() != null) {
				if ((data.getExtras().get("portrait_cartoon") != null)
						&& (requestCode == 0)) {
					cartoonResult(data);
				} else if ((data.getExtras().get("data") != null)
						&& (requestCode == 1)) {
					cameraResult(data);
				} else if ((data.getExtras().get("data") != null)
						&& (requestCode == 2)) {
					pictureResult(data);
				}
			} else if (data.getData() != null) {
				if (requestCode == 2)
					MIUIpictureResult(data);
			}

			if (portraitBitmap != null) {
				final File file = MobileUtil.saveBitmapToSDCard(
						user.getUser_id() + "+" + System.currentTimeMillis()
								+ ".png", portraitBitmap);
				showProgressDialog(getString(R.string.local_update_load_text));
				UploadPhotoRequest uploadPhotoRequest = new UploadPhotoRequest();
				uploadPhotoRequest.excute(AddPetActivity.this, null, null,
						"JPEG", file, new IHttpCallBack() {
							@Override
							public void success(String result) {
								dimissProgressDialog();
								try {
									UploadPhotoResponse updatePhotoResponse = new UploadPhotoResponse(
											new JSONObject(result));
									Common common = updatePhotoResponse
											.getCommon();
									if (common != null
											&& common
													.getReturnCode()
													.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
										photoUrl = updatePhotoResponse
												.getPhotoUrl();
										PortraitLoaderUtil.load(
												AddPetActivity.this, header,
												null, photoUrl,
												R.drawable.head_icon,
												R.drawable.head_icon);

									} else {
										Toast.makeText(AddPetActivity.this,
												common.getErrorMsg(),
												Toast.LENGTH_LONG).show();
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}

							@Override
							public void fail(String result) {
								dimissProgressDialog();
								try {
									UploadPhotoResponse updatePhotoResponse = new UploadPhotoResponse(
											new JSONObject(result));
									Common common = updatePhotoResponse
											.getCommon();
									Toast.makeText(AddPetActivity.this,
											common.getErrorMsg(),
											Toast.LENGTH_LONG).show();
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}
						});

			} else {

			}
			break;
		default:
			break;
		}
	}

	public byte[] getBitmapByte(Bitmap bitmap) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
		try {
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}

	// 缺图像裁剪压缩
	protected void cameraResult(Intent data) {
		portraitBitmap = (Bitmap) data.getExtras().get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
	}

	// 缺图像裁剪压缩
	protected void pictureResult(Intent data) {
		portraitBitmap = (Bitmap) data.getExtras().get("data");
	}

	// 缺图像裁剪压缩
	protected void MIUIpictureResult(Intent data) {
		Uri originalUri = data.getData();
		if (originalUri != null) {
			try {
				portraitBitmap = MediaStore.Images.Media.getBitmap(
						this.getContentResolver(), originalUri);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	protected void cartoonResult(Intent data) {
		Resources res = getResources();
		portraitBitmap = BitmapFactory.decodeResource(
				res,
				Integer.valueOf(data.getExtras().get("portrait_cartoon")
						.toString()));
	}

	protected SimpleAdapter getMenuAdapter(String[] menuNameArray) {
		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < menuNameArray.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("itemText", menuNameArray[i]);
			data.add(map);
		}
		SimpleAdapter simperAdapter = new SimpleAdapter(this, data,
				R.layout.item_menu_text, new String[] { "itemText" },
				new int[] { R.id.item_text });
		return simperAdapter;
	}

	@Override
	public void chooseDaySuccess(int year, int mouth, int day) {
		enter_birth.setText(year + "-" + mouth + "-" + day);
	}
}
